//
//  RecordViewController.m
//  SoundPill
//
//  Created by 宋旭东®Des on 15/1/17.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "RecordViewController.h"
#import "MMDrawerController.h"
#import "UIViewExt.h"
#import "record_login.h"
#import "AppDelegate.h"
#import "JCAlertView.h"
#define photoCell @"photoCell"
#define addImage @"addImage"

@interface RecordViewController ()<UINavigationControllerDelegate,
    SFCountdownViewDelegate, UIActionSheetDelegate>
{
    UIImage  * img;
    NSString *typeString;
    //////作品包路径//////
    NSString *workSpace;
    NSString *workTime;
    NSString *mp3FilePath;
    NSString *mp3FileName;
    NSString *waveformPath;
    //////音频时长///////
    NSString *audioDuration;
    float recordDuration;
}
@property (strong, nonatomic) UIScrollView *scroll;
@property (strong, nonatomic) UIView *parentView;
@property (strong, nonatomic) UIButton *play_recordButton;
@property (assign, nonatomic) NSInteger buttonState;//按钮状态 0为录音，1为停止，2为播放
@property (strong, nonatomic) NSURL *audioURL;
@property (strong, nonatomic) SFCountdownView *countDown;
@property (strong, nonatomic) UIImageView *recorderImage;
@property (strong, nonatomic) UIImageView *twirRight;
@property (strong, nonatomic) UIImageView *twirLeft;
@property (strong, nonatomic) UIBarButtonItem *editButton;
@property (strong, nonatomic) NSDate *senddate;
@property (strong, nonatomic) NSTimer *recorderTimer;
@property (strong, nonatomic) NSTimer *playerTimer;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIButton *button;
@end

@implementation RecordViewController
- (instancetype)initWithType:(NSString *)type detile:(NSString *)detile{
    self = [super init];
    if (self) {
        type = [NSString stringWithFormat:@"#%@#",[type stringByReplacingOccurrencesOfString:@"#" withString:@""]];
        if (detile) {
            typeString = [NSString stringWithFormat:@"#%@#",detile];
        } else {
            typeString = type;
        }
//        typeString = [typeString stringByReplacingOccurrencesOfString:@"#" withString:@""];
        
//        self.isSaved = [NSNumber numberWithBool:NO];//判断是否保存过
        self.hidesBottomBarWhenPushed = YES;
        //从相册选择 返回
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentSize:) name:@"scrollContentSize" object:nil];
        //根据录音时间设置 scrollview 滚动区域
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backFromTag:) name:@"backFromTag" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioPlayer" object:nil];
        //VC 中调用 波形 view 中的停止播放
        [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
//        [self findDraftFile];
    }
    return self;
}


- (void)changeContentSize:(NSNotification *)notification
{
    //获取波形 view 的宽度
    NSNumber *width = notification.object;
//    NSLog(@"contentSize == %@", width);
    _scroll.contentSize = CGSizeMake(width.floatValue + self.view.frame.size.width / 2, 0);
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioBeforRecord" object:nil];
        [AppDelegate shareDelegate].indicator.state = NAKPlaybackIndicatorViewStatePaused;
        [[AppDelegate shareDelegate] setUpMusicIndicator];
        [AppDelegate shareDelegate].playerStateBtn.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    //导航栏背景
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    //创建波形图 view
    [self createView];
    //创建录音四态按钮 导航栏按钮
    
    //录音时底部动画
    self.parentView = [[UIView alloc] initWithFrame:CGRectMake(0, _scroll.bounds.size.height + 15, self.view.frame.size.width, self.view.frame.size.height * 0.329) ];
//    NSLog(@"%f", self.view.frame.size.height);
    [self.view addSubview:_parentView];
//    _parentView.backgroundColor = [UIColor redColor];
    self.recorderImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _parentView.bounds.size.width, _parentView.bounds.size.height)];
    [_recorderImage setImage:[UIImage imageNamed:@"recorderImage"]];
    [_parentView addSubview:_recorderImage];
    
    //左边转动 view
    self.twirLeft = [[UIImageView alloc] initWithFrame:CGRectMake(6, -4, 127+8, 127+8)];
    _twirLeft.image = [UIImage imageNamed:@"twirl_1"];
    [_recorderImage addSubview:_twirLeft];
    //右边转动 view
    self.twirRight = [[UIImageView alloc] initWithFrame:CGRectMake(178, -4, 127 + 8, 127 + 8)];
    _twirRight.image = [UIImage imageNamed:@"twirl_1"];
    [_recorderImage addSubview:_twirRight];
    if ([UIScreen mainScreen].bounds.size.height == 667) {
        _twirLeft.frame = CGRectMake(6, -5, 147 + 12, 147 + 12);
        _twirRight.frame = CGRectMake(209, -5, 147 + 12, 147 + 12);
    } else if ([UIScreen mainScreen].bounds.size.height == 736) {
        _twirLeft.frame = CGRectMake(6, -6, 165 + 12, 165 + 12);
        _twirRight.frame = CGRectMake(230, -6, 165 + 12, 165 + 12);
    }
    //录音完成后底部已选照片相册
    [self createButton];
//    [self createPhotoView];
    
    //点击录音按钮 倒计时 view
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeButtonNameToPlay:) name:@"play" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeButtonNameToPause:) name:@"pause" object:nil];
}
- (void)changeButtonNameToPlay:(NSNotification *)Notification{
    [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"endRecording"] forState:UIControlStateNormal];
    _buttonState = 2;
    [_recorderTimer invalidate];
    _recorderTimer = nil;
}
- (void)changeButtonNameToPause:(NSNotification *)Notification{
    [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    _buttonState = 3;
}

- (void)createButton{
    //取消按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setFrame:CGRectMake(0, 0, 30, 30)];
    [cancelButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
     [cancelButton addTarget:self action:@selector(touchCancelButton) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"close"] style:UIBarButtonItemStylePlain target:self action:@selector(touchCancelButton)];
    cancel.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = cancel;
    //录音播放按钮
    self.play_recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_play_recordButton setFrame:CGRectMake(self.view.frame.size.width / 2 - ((self.view.frame.size.width  -  20) / 2), _parentView.frame.origin.y + _parentView.frame.size.height + 30, (self.view.frame.size.width  -  20), self.view.frame.size.width * 0.163)];
    [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"recording"] forState:UIControlStateNormal];
    [_play_recordButton addTarget:self action:@selector(recordOrStopOrPlay) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_play_recordButton];
    self.buttonState = 0;
    
    UILabel *typeLable = [[UILabel alloc] initWithFrame:CGRectMake(0, _play_recordButton.bottom, self.view.width, self.view.height - 64 - _play_recordButton.bottom)];
    typeLable.text = typeString;
    typeLable.font = [UIFont systemFontOfSize:14];
    typeLable.backgroundColor = [UIColor clearColor];
    typeLable.textAlignment = NSTextAlignmentCenter;
    typeLable.textColor = [UIColor colorWithWhite:0.677 alpha:1.000];
    [self.view addSubview:typeLable];
    
    //编辑按钮
    UIButton *edit = [UIButton buttonWithType:UIButtonTypeCustom];
    [edit setFrame:CGRectMake(0, 0, 30, 30)];
    [edit setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    [edit addTarget:self action:@selector(goToEdit:) forControlEvents:UIControlEventTouchUpInside];
    self.editButton = [[UIBarButtonItem alloc] initWithCustomView:edit];
    if (_isDraft.boolValue == YES) {
        _buttonState = 2;
        [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"endRecording"] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = _editButton;
    }
}
- (void)createView{
    //背景滚动视图
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3)];
    _scroll.contentSize = CGSizeMake(0, 0);
    _scroll.backgroundColor = [UIColor whiteColor];
    _scroll.showsHorizontalScrollIndicator = NO;
    _scroll.bounces = NO;
    [self.view addSubview:_scroll];
    //绘制波形视图
    self.recView = [[RecordingView alloc] initWithFrame:CGRectMake(0, 0, 10000, _scroll.bounds.size.height)];
//    _recView.backgroundColor = [UIColor clearColor];
    [_scroll addSubview:_recView];
    [_recView getScrollView:_scroll];

    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 3, 40)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.text = @"00'00\"00";//mm'' ss\" ";
    _titleLabel.font = [UIFont fontWithName:@"Arial" size:24];//systemFontOfSize:24];
    _titleLabel.textColor = [UIColor blackColor];
    self.navigationItem.titleView = _titleLabel;
//    判断是否草稿箱
    if (_isDraft.boolValue == YES) {
        [_recView getAudioPath:_draftAudioPath draftAuioWaveform:_waveform];
        _recView.averagerPowerComplete = [NSMutableArray arrayWithArray:_waveform];
        NSError *error = nil;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *DouNiu = [strUrl stringByAppendingPathComponent:@"DouNiu"];
        NSArray *fileList = [[NSArray alloc] init];
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        fileList = [fileManager contentsOfDirectoryAtPath:DouNiu error:&error];
        NSString *workName = [fileList lastObject];
        workTime = workName;
        workSpace = [DouNiu stringByAppendingPathComponent:workName];
        _audioURL = [NSURL URLWithString:[workSpace stringByAppendingFormat:@"/%@.mp3", workTime]];
        recordDuration = _recView.player.duration;
        int m = _recView.player.duration / 60;
        int s = ((int) _recView.player.duration) % 60;
        int ss = (_recView.player.duration - ((int) _recView.player.currentTime));
        self.titleLabel.text =  [NSString stringWithFormat:@"%.2d'%.2d\"%.2d", m, s,ss];
        audioDuration = [NSString stringWithFormat:@"%.2d'%.2d\"", m, s];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[workSpace stringByAppendingPathComponent:@"classic"]];

        [AppDelegate shareDelegate].startTag = [dic valueForKey:@"tag"];
        [AppDelegate shareDelegate].topicString = [dic valueForKey:@"topic"];
        [AppDelegate shareDelegate].topicIsPrivate = [dic valueForKey:@"topicPrivate"];
        if ([[dic valueForKey:@"topic"] length] > 0) {
            typeString =[NSString stringWithFormat:@"#%@#", [dic valueForKey:@"topic"]];
        } else {
            typeString = [NSString stringWithFormat:@"#%@#",[[dic valueForKey:@"tag"]stringByReplacingOccurrencesOfString:@"#" withString:@""]];
        }
        if ([[dic allKeys] containsObject:@"topicDetail"]) {
            [AppDelegate shareDelegate].topicDetailString = [dic valueForKey:@"topicDetail"];
        }
    }
    //创建波形图上的刻度
    for (int i = 0; i <= 9; i++) {
        NSString *str = [NSString stringWithFormat:@"min%d.png", i+1];
        if (i <= 9) {
            UIImageView *kedu = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 2400 * i, 0, 2400, 20)];
            kedu.image = [UIImage imageNamed:str];
            [_scroll addSubview:kedu];
        } else {
            UIImageView *kedu = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 + 2400 * i, 0, 2432, 20)];
            kedu.image = [UIImage imageNamed:str];
        }
    }
    //刻度下方灰线
    UIImageView *buttomline = [[UIImageView alloc] initWithFrame:CGRectMake(0, 19, self.view.frame.size.width, 2)];
    buttomline.image = [UIImage imageNamed:@"recording_grayline"];
    [self.view addSubview:buttomline];
    //波形纵向中央白线
    UIImageView *grayLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, (self.view.frame.size.height / 3 + 20) / 2 - 1, self.view.bounds.size.width, 1)];
    grayLine.image = [UIImage imageNamed:@"whiteBlackLine"];
    [self.view addSubview:grayLine];
    //波形横向中央红线
    UIImageView *redLine = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 2 - 2.5, 20, 5, self.view.frame.size.height / 3 - 20)];
    redLine.image = [UIImage imageNamed:@"red"];
    [self.view addSubview:redLine];
    //波形图底部灰线
    UIImageView *waveformGrayLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, redLine.frame.size.height + redLine.frame.origin.y, self.view.frame.size.width, 0.7)];
    waveformGrayLine.image = [UIImage imageNamed:@"recording_grayline"];
    [self.view addSubview:waveformGrayLine];

//创建 navigation titleView
    
}
#pragma mark -
#pragma mark 录音按钮事件
- (void)recordOrStopOrPlay{
    if (_buttonState == 0){
//        调用倒计时
        self.countDown = [[SFCountdownView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _countDown.delegate = self;
        _countDown.backgroundAlpha = 0;
        _countDown.countdownFrom = 3;
        _countDown.finishText = @"1";
        [self.view addSubview:_countDown];
//        倒计时开始，倒计时结束后开始录音
        [self.countDown start];
        _scroll.userInteractionEnabled = NO;
        [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"isRecording"] forState:UIControlStateNormal];
//        设置状态为1，即录音
        self.buttonState = 1;
    }
    else if (_buttonState == 1){
//        判断录音时长，大于十秒可以停止
        [self stopRecording];
    }
    else if (_buttonState == 2){
//        开始播放
        [self.recView playStart];
//        播放时关闭 scrollview 用户交互
        _scroll.userInteractionEnabled = NO;
        [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
//        判断播放的定时器是否存在，存在就开始，不存在就创建
        if (_playerTimer) {
            [_playerTimer setFireDate:[NSDate distantPast]];
        } else {
            self.playerTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(getCurrentTime) userInfo:nil repeats:YES];
        }
        self.buttonState = 3;
    } else if (_buttonState == 3){
//        暂停
        [self.recView playPause];
//        用户交互打开
        _scroll.userInteractionEnabled = YES;
//        暂停播放定时器
        [_playerTimer setFireDate:[NSDate distantFuture]];
        [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"endRecording"] forState:UIControlStateNormal];
        self.buttonState = 2;
//        按钮状态置为播放
    }
}
- (void)stopRecording{
    if ( _recView.record.currentTime >= 11.0) {
        [self.recView stopRecord];
        _scroll.userInteractionEnabled = YES;
        [_recorderTimer invalidate];
        _recorderTimer = nil;
        self.navigationItem.rightBarButtonItem = _editButton;
        [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"endRecording"] forState:UIControlStateNormal];
        //            停止录音时的磁带动画
        [_twirRight.layer removeAllAnimations];
        [_twirLeft.layer removeAllAnimations];
        
        self.buttonState = 2;
        //            停止后调用转 mp3方法
        dispatch_async(dispatch_queue_create(0, 0), ^{
            [self toMp3];
        });
        
        dispatch_async(dispatch_queue_create(0, 0), ^{
            NSMutableArray *smallAverager = [[NSMutableArray alloc] init];
                if (recordDuration <= 240.0) {
                    for (int i = 0 ; i < _recView.averagerPowerComplete.count; i++) {
                        if (i % 6 == 0) {
                            [smallAverager addObject:_recView.averagerPowerComplete[i]];
                        }
                    }
                } else {
                 int temp =  (int)_recView.averagerPowerComplete.count / 800;
                    for (int i = 0; i < _recView.averagerPowerComplete.count; i++) {
                        if (i % temp == 0) {
                            [smallAverager addObject:_recView.averagerPowerComplete[i]];
                        }
                    }
                }
            NSDictionary * waveform = [NSDictionary dictionaryWithObjectsAndKeys:smallAverager, @"peaks", nil];
            NSString *str = [waveform JSONString];
            waveformPath = [workSpace stringByAppendingPathComponent:@"waveform.json"];
            [str writeToFile:waveformPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
            [_recView.averagerPowerComplete writeToFile:[workSpace stringByAppendingPathComponent:@"waveformComplete"] atomically:YES];
#pragma 保存话题描述
            NSDictionary *classic = nil;
            if ([AppDelegate shareDelegate].topicDetailString.length > 0) {
                classic = [NSDictionary dictionaryWithObjectsAndKeys:[AppDelegate shareDelegate].startTag,@"tag",[AppDelegate shareDelegate].topicString,@"topic",[AppDelegate shareDelegate].topicDetailString,@"topicDetail",[AppDelegate shareDelegate].topicIsPrivate,@"topicPrivate", nil];
            } else {
                classic = [NSDictionary dictionaryWithObjectsAndKeys:[AppDelegate shareDelegate].startTag,@"tag",[AppDelegate shareDelegate].topicString,@"topic",[AppDelegate shareDelegate].topicIsPrivate,@"topicPrivate", nil];
            }
            NSString *classicPath = [workSpace stringByAppendingPathComponent:@"classic"];
            [classic writeToFile:classicPath atomically:YES];
        });
        
    } else {
        //            如果小于11秒 提示
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"至少录制11秒" delegate: nil cancelButtonTitle:nil otherButtonTitles:nil];
//        [alert show];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [alert dismissWithClickedButtonIndex:0 animated:YES];
//        });
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"至少录制11秒";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    }
}
#pragma mark -
#pragma mark 取消按钮点击事件
- (void)touchCancelButton{
    if (_isDraft.boolValue == YES) {
        if (_recView.player == nil) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [JCAlertView showTwoButtonsWithTitle:@"提醒" Message:@"是否保存该作品至草稿箱" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"不保存" Click:^{
                if ([_recView.record isRecording]) {
                    [self.recView stopRecord];
                    //            _scroll.userInteractionEnabled = YES;
                    [_recorderTimer invalidate];
                    _recorderTimer = nil;
                } else if ([_recView.player isPlaying]){
                    [_recView.player stop];
                    [_playerTimer invalidate];
                    _playerTimer = nil;
                }
                
//                NSError *err;
//                [[NSFileManager defaultManager] removeItemAtPath:workSpace error:&err];
                if (_recorderTimer == nil) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"保存" Click:^{
                if ([_recView.record isRecording]) {
                    [self stopRecording];
                } else if ([_recView.player isPlaying]){
                    [_recView.player stop];
                    [_playerTimer invalidate];
                    _playerTimer = nil;
                }
                if (_recorderTimer == nil) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }

            }];
        }
    } else {
        if (_recView.record == NULL || _recView.record == nil) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [JCAlertView showTwoButtonsWithTitle:@"提醒" Message:@"是否保存该作品至草稿箱" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"不保存" Click:^{
                if ([_recView.record isRecording]) {
                    [self.recView stopRecord];
                    //            _scroll.userInteractionEnabled = YES;
                    [_recorderTimer invalidate];
                    _recorderTimer = nil;
                } else if ([_recView.player isPlaying]){
                    [_recView.player stop];
                    [_playerTimer invalidate];
                    _playerTimer = nil;
                }
                
                NSError *err;
                [[NSFileManager defaultManager] removeItemAtPath:workSpace error:&err];
                if (_recorderTimer == nil) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"保存" Click:^{
                if ([_recView.record isRecording]) {
                    [self stopRecording];
                } else if ([_recView.player isPlaying]){
                    [_recView.player stop];
                    [_playerTimer invalidate];
                    _playerTimer = nil;
                }
                if (_recorderTimer == nil) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }];
        }
    }
    [AppDelegate shareDelegate].topicDetailString = nil;
    [AppDelegate shareDelegate].playerStateBtn.hidden = NO;
}
#pragma mark -
#pragma mark 跳转编辑页
- (void)goToEdit:(id)sender{
    if ([_recView.player isPlaying]) {
        [_recView playPause];
        _buttonState = 2;
        [_play_recordButton setBackgroundImage:[UIImage imageNamed:@"endRecording"] forState:UIControlStateNormal];
    }
    EditViewController *editController = [[EditViewController alloc] init];
    if (_isDraft.boolValue == YES) {
        editController.isDraft = [NSNumber numberWithBool:YES];
    } else {
        editController.isDraft = [NSNumber numberWithBool:NO];
    }
        [editController getImageArray:nil auidoURL:_audioURL waveArray:_recView.averagerPowerComplete workSpace:workSpace workTime:workTime textArray:nil audioDurationStr:audioDuration audioDurationFloat:recordDuration];
        [self.navigationController pushViewController:editController animated:YES];
}

#pragma mark -
#pragma mark 获取当前时间
//将当前时间作为录音作品文件夹的文件夹名
- (NSString *)getTimeString{
    self.senddate=[NSDate date];
//    NSLog(@"%f", [_senddate timeIntervalSince1970]);
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmm"];
    NSString *locationString=[dateformatter stringFromDate:_senddate];
    return locationString;
}
#pragma mark -
#pragma mark 录音文件地址
//获取录音文件保存地址
- (NSURL *)fullPathAtDouNiu{
    workTime = [self getTimeString];
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *DouNiu = [strUrl stringByAppendingPathComponent:@"DouNiu"];
    workSpace = [DouNiu stringByAppendingFormat:@"/%@", workTime];
    if (![fileManager fileExistsAtPath:DouNiu]) {
        [fileManager createDirectoryAtPath:DouNiu withIntermediateDirectories:YES attributes:nil error:&error];
        }
    if (![fileManager fileExistsAtPath:workSpace]) {
        [fileManager createDirectoryAtPath:workSpace withIntermediateDirectories:YES attributes:nil error:&error];
    }
    NSURL *recordedFile = [NSURL fileURLWithPath:[workSpace stringByAppendingFormat:@"/%@.caf", workTime]];
    return recordedFile;
}


#pragma mark -
#pragma mark 倒计时完成
- (void)countdownFinished:(SFCountdownView *)view{
    [self.countDown removeFromSuperview];
//    执行波形 view 中的开始录音方法并获取录音文件存储地址
    [self.recView startForFilePath:[self fullPathAtDouNiu]];
    [self startAnimation];
//    启动录音定时器
    self.recorderTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(getCurrentTime) userInfo:nil repeats:YES];
}
//navigation titleview
- (void)getCurrentTime{
//    NSLog(@"%f", _recView.record.currentTime);
    if (_recView.record.isRecording) {
        recordDuration = _recView.record.currentTime;
        int m = _recView.record.currentTime / 60;
        int s = ((int) _recView.record.currentTime) % 60;
        int ss = (_recView.record.currentTime - ((int) _recView.record.currentTime)) * 100;
        self.titleLabel.text =  [NSString stringWithFormat:@"%.2d'%.2d\"%.2d", m, s, ss];
        audioDuration = [NSString stringWithFormat:@"%.2d'%.2d\"", m, s];
        if (_recView.record.currentTime >= 480) {
            [self stopRecording];
        }
    }
    if (_recView.player.isPlaying) {
        int m = _recView.player.currentTime / 60;
        int s = ((int) _recView.player.currentTime) % 60;
        int ss = (_recView.player.currentTime - ((int) _recView.player.currentTime)) * 100;
        self.titleLabel.text =  [NSString stringWithFormat:@"%.2d'%.2d\"%.2d", m, s,ss];
    }
}
#pragma mark -
#pragma mark 录音动画
//磁带转动动画
- (void)startAnimation{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 1;
    rotationAnimation.repeatCount = 1000;//你可以设置到最大的整数值
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [_twirLeft.layer addAnimation:rotationAnimation forKey:@"Rotation"];
    [_twirRight.layer addAnimation:rotationAnimation forKey:@"Rotation"];

}
#pragma mark-
#pragma mark 音频转码
- (void)toMp3{
    NSString *cafFilePath = [workSpace stringByAppendingFormat:@"/%@.caf", workTime];
    mp3FileName = [NSString stringWithFormat:@"/%@.mp3", workTime];
    mp3FilePath = [workSpace stringByAppendingString:mp3FileName];
//    NSLog(@"%@", mp3FilePath);
    self.audioURL = [NSURL URLWithString:mp3FilePath];
    @try {
        int read, write;
         FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_num_channels(lame, 1); // 单声道
        lame_set_in_samplerate(lame, 22050);
//        lame_set_brate(lame, );// 压缩的比特率为128K
        lame_set_VBR(lame, vbr_default);
//        lame_set_mode(lame, 1);
//        lame_set_quality(lame, 2);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
//        NSLog(@"%@",[exception description]);
    }
    @finally {
    }
}
@end
